import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';

import '../../../../core/utils/show_toast.dart';
import '../../../../data/controllers/tools_controller.dart';
import '../models/tool.dart';

part 'tools_state.dart';
part 'tools_event.dart';

class ToolsCubit extends Bloc<ToolsEvent, ToolsState> {
  ToolsCubit(ToolsState initialState) : super(ToolsInitial()){
    on<ToolsInitialEvent>(_onInitialize);
    on<GetToolsEvent>(_onGetTools);
    on<SelectModeEvent>(_onChangeSelectMode);
    on<SelectToolEvent>(_onSelectTool);
  }

  static ToolsCubit get(context) => BlocProvider.of(context);
  List<ToolModel> tools = [];
  List<ToolModel> selectedTools = [];
  bool selectMode = false;

  _onInitialize(
      ToolsInitialEvent event,
      Emitter<ToolsState> emit,
      )async {
    tools = [];
    emit(ToolsLoading());
    await ToolsController.getAllTools().catchError((e){
      emit(ToolsError());
      return null;
    }).then((value){
      if(value != null && value.state) {
        add(SelectModeEvent(mode: false));
        tools = List<ToolModel>.generate(value.data.length, (index) => ToolModel.fromJson(value.data[index]));
        emit(ToolsDone());
      }else if(value != null){
        showMessage(value.message);
        emit(ToolsError());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
      }
    });
  }


  _onGetTools(
      GetToolsEvent event,
      Emitter<ToolsState> emit,
      )async{
    tools = [];
    emit(ToolsLoading());
    await ToolsController.getAllTools().catchError((e){
      emit(ToolsError());
      return null;
    }).then((value){
      if(value != null && value.state) {
        tools = List<ToolModel>.generate(value.data.length, (index) => ToolModel.fromJson(value.data[index]));
        emit(ToolsDone());
      }else if(value != null){
        showMessage(value.message);
        emit(ToolsError());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
      }
    });
  }


  _onChangeSelectMode(
      SelectModeEvent event,
      Emitter<ToolsState> emit,
      )async{
    selectMode = event.mode;
    if(event.tool != null){
      selectedTools.add(event.tool!);
    }
    if(!event.mode){
      selectedTools.clear();
    }
    emit(SelectModeUpdate( mode: selectMode));
  }

  _onSelectTool(
      SelectToolEvent event,
      Emitter<ToolsState> emit,
      )async{
    if(event.isSelected){
      selectedTools.add(event.tool);
    }else{
      selectedTools.remove(event.tool);
    }
    emit(SelectTool(tool: event.tool,isSelected: event.isSelected));
  }


/*  _onAddToGym(
      AddToExerciseEvent event,
      Emitter<ToolsState> emit,
      )async{
    emit(AddToolToExerciseLoading(tool: event.tool));



  }*/

  Future onRefresh()async{
    add(ToolsInitialEvent());
  }
}
